﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Hutech.Authentication.Library.Web.Framework;
using Resources;
using Hutech.Authentication.Library.Business.WebHelpers;
using log4net;
using Hutech.Authentication.Library.Business;
using System.Globalization;
using System.Text;
using System.Data;

namespace Hutech.CRM.Web.Controls.ManageRoleAndModule
{
    public partial class ListUserInRole : System.Web.UI.UserControl
    {
        #region Properties
        protected int pageNumber
        {
            get
            {
                if (ViewState["pageNumber"] != null)
                {
                    try { return Convert.ToInt32(ViewState["pageNumber"].ToString()); }
                    catch { return 1; } // add
                }
                return 1;
            }
            set
            {
                ViewState["pageNumber"] = value;
            }
        }
        public int pageSize
        {
            get
            {
                if (ViewState["PageSize"] != null)
                {
                    try { return Convert.ToInt32(ViewState["PageSize"].ToString()); }
                    catch { return 25; } // add
                }
                return 25;
            }
            set
            {
                ViewState["PageSize"] = value;
            }
        }
        private int totalPages = 1;
        #endregion

        #region Variable
        private Guid roleID = Guid.Empty;
        private Role role;
        protected string DeleteLinkImage = "~/Data/SiteImages/" + WebConfigSettings.DeleteLinkImage;
        #endregion

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            this.Load += new EventHandler(this.Page_Load);
            LinkButtonAddUserInRole.Click += new EventHandler(LinkButtonAddUserInRole_Click);
            rptRoleMembers.ItemCommand += new RepeaterCommandEventHandler(rptRoleMembers_ItemCommand);
            rptRoleMembers.ItemDataBound += new RepeaterItemEventHandler(rptRoleMembers_ItemDataBound);
            PopupAddUser1.ReloadData += new EventHandler(PopupAddUser1_ReloadData);

            pgrItems.Command += new System.Web.UI.WebControls.CommandEventHandler(pgrItems_Command);
        }

        private void Page_Load(object sender, EventArgs e)
        {
            if (!WebUser.IsAdminOrRoleAdmin)
            {
                SiteUtils.RedirectToAccessDeniedPage(this);
                return;
            }

            //SecurityHelper.DisableBrowserCache();

            LoadParams();
            PopulateLabels();

            if (!Page.IsPostBack)
            {
                BindRepeater();
            }
        }

        #region All event
        void pgrItems_Command(object sender, System.Web.UI.WebControls.CommandEventArgs e)
        {
            pageNumber = Convert.ToInt32(e.CommandArgument);
            pgrItems.CurrentIndex = pageNumber;
            BindRepeater();
        }
        //Load all user is not authencation. 
        void LinkButtonAddUserInRole_Click(object sender, EventArgs e)
        {
            PopupAddUser1.Show(roleID);
            BindRepeater();
        }
        
        /// <summary>
        /// excute event click delete
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        void rptRoleMembers_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "delete")
            {
                Guid userId = Guid.Parse(e.CommandArgument.ToString());
                SiteUser user = new SiteUser(userId);
                // Neu so luong role cua user lon hon 1 thi them moi.
                //Neu bang 1 ta thay doi quyen hien tai thanh quyen moi. Vi khi = 1, user co quyen UnAuthenticated
                if (Role.CountRoleByUser(user.UserId) > 1)
                    Role.RemoveUser(roleID, user.UserId);
                else
                    Role.ChangeUserToNotAuthenticated(user.UserId);
            }
            BindRepeater();
            this.pnlMain.Update();
            //WebUtils.SetupRedirect(this, Request.RawUrl);
        }
        void rptRoleMembers_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            ImageButton btnDelete = e.Item.FindControl("btnDelete") as ImageButton;
            if (btnDelete != null)
            {
                btnDelete.AlternateText = Resource.ManageUsersRemoveFromRoleButton;
                btnDelete.ToolTip = Resource.ManageUsersRemoveFromRoleButton;
                UIHelper.AddConfirmationDialog(btnDelete, Resource.RolesRemoveUserWarning);
            }
        }
        void PopupAddUser1_ReloadData(object sender, EventArgs e)
        {
            BindRepeater();
            this.pnlMain.Update();
        }
        #endregion

        #region Load All data
        private void PopulateLabels()
        {
            LinkButtonAddUserInRole.Text = Resource.SecurityAddExistingButton;
        }
        private void LoadParams()
        {
            roleID = WebUtils.ParseGuidFromQueryString("roleid", Guid.Empty);
        }
        private void BindRepeater()
        {
            this.rptRoleMembers.DataSource = SiteUser.GetPageByRoleID(roleID, pageNumber, pageSize, out totalPages);
            this.rptRoleMembers.DataBind();

            if (this.totalPages > 1)
            {
                pgrItems.ShowFirstLast = true;
                pgrItems.PageSize = this.pageSize;
                pgrItems.PageCount = this.totalPages;
            }
            else
            {
                pgrItems.Visible = false;
            }
        }
        #endregion
    }
}
